package com.glorysoft.sunnypda.base;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import com.glorysoft.sunnypda.R;
import com.glorysoft.sunnypda.entity.LogEntity;
import com.glorysoft.sunnypda.entity.net.BaseRequestBean;
import com.glorysoft.sunnypda.entity.net.BaseResponseBean;
import com.glorysoft.sunnypda.entity.net.HeaderBean;
import com.glorysoft.sunnypda.entity.net.NetRequestBean;
import com.glorysoft.sunnypda.ui.reportrepair.ReportRepairActivity;
import com.glorysoft.sunnypda.utils.ChangeLanguageHelper;
import com.glorysoft.sunnypda.utils.NotificationClickReceiver;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_InitUtils;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;

import org.apache.commons.lang3.StringEscapeUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import okhttp3.OkHttpClient;
import rxhttp.wrapper.cookie.CookieStore;
import rxhttp.wrapper.param.RxHttp;
import rxhttp.wrapper.ssl.HttpsUtils;


/**
 * FileName: MyApp
 * Author: XJH
 * Date: 2020/5/12 11:30
 * Description:
 * History:
 */
public class MyApp extends Application {

    public static Context app;
    private static MyApp instance;
    private final Timer timer = new Timer();
    private PendingIntent pi;
    private NotificationManager notificationManager;
    private TimerTask task;
    private Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            if (Constant.Companion.getCURRENT_USER_NAME() != null
            && !Constant.Companion.getCURRENT_USER_NAME().equals("") &&
                    !Constant.Companion.isReportRepairActivity()) {
                FreeUI_EntityCallBack<BaseResponseBean<LogEntity>> callBack = new FreeUI_EntityCallBack<BaseResponseBean<LogEntity>>
                        (new TypeToken<BaseResponseBean<LogEntity>>() {
                        }.getType()) {

                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(Response<BaseResponseBean<LogEntity>> response) {
                        if (response.body().getResponse().getBody() != null || !response.body().getResponse().getBody().equals("")) {
                            if (response.body().getResponse().getBody().getLOGLIST() != null &&
                                    response.body().getResponse().getBody().getLOGLIST().size() > 0) {
                                ArrayList<LogEntity.LogListEntity> listitme = response.body().getResponse().getBody().getLOGLIST();
                                for (int i=0; i<listitme.size(); i++) {
                                    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                        Notification notification = new Notification.Builder(app, "defaultss")
                                                .setContentTitle(getString(R.string.app_name))
                                                .setContentText(listitme.get(i).getLOGMESSAGETEXT())
                                                .setWhen(System.currentTimeMillis())
                                                .setSmallIcon(R.mipmap.ic_launcher)
                                                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                                                .setAutoCancel(true)
                                                .setContentIntent(pi)
                                                .build();
                                        notificationManager.notify(i, notification);
                                    }else {
                                        Notification notification = new Notification.Builder(app)
                                                .setContentTitle(getString(R.string.app_name))
                                                .setContentText(listitme.get(i).getLOGMESSAGETEXT())
                                                .setWhen(System.currentTimeMillis())
                                                .setSmallIcon(R.mipmap.ic_launcher)
                                                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                                                .setAutoCancel(true)
                                                .setContentIntent(pi)
                                                .build();
                                        notificationManager.notify(i, notification);
                                    }

                                }
                            }
                        }
                    }

                    @Override
                    public void onError
                            (Response<BaseResponseBean<LogEntity>> response) {
                        super.onError(response);
                    }
                };
                Map<String, String> map = new HashMap<>();
                NetRequestBean format = new NetRequestBean<Object>();
                format.setBody(map);
                format.setHeader(new HeaderBean("VIEW_PDA_EQP_LOG_BY_OPID"));
                BaseRequestBean message = new BaseRequestBean();
                message.setRequest(format);
                HashMap<String, String> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("senderId","EAP2CPCSender");
                objectObjectHashMap.put("requestMessage",StringEscapeUtils.unescapeJson(new Gson().toJson(message)));
                objectObjectHashMap.put("timeOut","5000");

                FreeApi_LogUtils.saveErrorMessages(StringEscapeUtils.unescapeJson(new Gson().toJson(message)),"请求JSON");
                FreeApi_NetUtils.requestPostNet(Constant.Companion.getREQUEST_URL_DEBUG() + "/VIEW_PDA_EQP_LOG_BY_OPID", this, objectObjectHashMap, callBack);
            }
            super.handleMessage(msg);
        }
    };

    public static MyApp getInstance() {
        return instance;
    }

    // 获取有限网IP
    private static String getLocalIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {

        }
        return "0.0.0.0";

    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        app = getApplicationContext();
        FreeUI_InitUtils.init(getApplicationContext(), this, false, 60 * 1000L, 0);
        FreeUI_InitUtils.setTheme(FreeApi_StaticMembers.THEME_GLORY);
        initRxHttp();
        Constant.Companion.setIMEI_ID(getMacAddress());
        Constant.Companion.setIP_ADDRESS(getIpAddress());


        //8.0 以后需要加上channelId 才能正常显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            String channelId = "defaultss";
            String channelName = "默认通知";
            createNotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        }

        Intent intent = new Intent(this, ReportRepairActivity.class);
        pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        new Handler().postDelayed(() -> showTimer(), 60000);

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        // 创建 channel
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        // 获取 notificationManager
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 注册 channel
        notificationManager.createNotificationChannel(channel);
    }

    private void showTimer() {
        task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };
        timer.schedule(task, new Date(), 60000);
    }

    @Override
    public void onTerminate() {
        //关闭定时任务
        timer.cancel();
        task.cancel();
        super.onTerminate();
    }

    public String getIpAddress() {
        NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            // 3/4g网络
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                //  wifi网络
                WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());
                return ipAddress;
            } else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
                // 有限网络
                return getLocalIp();
            }
        }
        return "";
    }

    private String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    private String getMacAddress() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return getMacDefault();
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            return getMacAddressM();
        }

        return getMacFromHardware();

    }

    private String getMacDefault() {
        String address = "未获取到MAC地址";
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        String macAddress = connectionInfo.getMacAddress();
        address = macAddress.toUpperCase(Locale.ENGLISH);
        return address;
    }

    private String getMacAddressM() {
        String address = "未获取到MAC地址";
        try {
            address = new BufferedReader(new FileReader("/sys/class/net/wlan0/address")).readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return address;
    }

    private String getMacFromHardware() {
        try {
            ArrayList<NetworkInterface> list = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : list) {
                if (!"wlan0".equalsIgnoreCase(nif.getName())) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null || macBytes.length == 0) {
                    continue;
                }
                StringBuilder result = new StringBuilder();
                for (byte b : macBytes) {
                    result.append(String.format("%02X", b));
                }
                return result.toString().toUpperCase();

            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "未获取到MAC地址";
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        String LANGUAGE = FreeApi_SharePreferencesUtils.getSharePre("SUNNY_FILE", "LANGUAGE", "中文", this);
        switch (LANGUAGE) {
            case "中文":
            case "Chinese":
            case "Tiếng trung quốc":
                ChangeLanguageHelper.changeAppLanguage(this, Locale.SIMPLIFIED_CHINESE, "");
                break;
            case "英语":
            case "Tiếng anh":
            case "English":
                ChangeLanguageHelper.changeAppLanguage(this, Locale.ENGLISH, "");
                break;
            case "越南语":
            case "Việt nam":
            case "Vietnamese":
                Locale locale = new Locale("vi", "Vietnam");
                ChangeLanguageHelper.changeAppLanguage(this, locale, "");
                break;
        }
    }

    private void initRxHttp() {
        File file = new File(getExternalCacheDir(), "RxHttpCookie");
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieStore(file))
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) //添加信任证书
                .hostnameVerifier((hostname, session) -> true) //忽略host验证
                .build();
        //RxHttp初始化，自定义OkHttpClient对象，非必须
        RxHttp.init(client);
        RxHttp.setDebug(true);
        RxHttp.setOnParamAssembly(p -> {
            /*根据不同请求添加不同参数，子线程执行，每次发送请求前都会被回调
            如果希望部分请求不回调这里，发请求前调用Param.setAssemblyEnabled(false)即可
             */
            return p; //添加公共请求头
        });
    }

    private void sendNotification(String title,String text,int post) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        android.app.Notification.Builder builder;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            // id name 优先级
            NotificationChannel channel = new NotificationChannel("default","默认通知",NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("测试描述");
            channel.enableLights(true);//打开闪光灯
            channel.enableVibration(true);//打开震动
            channel.setVibrationPattern(new long[]{100,200,300,400});//震动频率
            channel.setLockscreenVisibility(android.app.Notification.VISIBILITY_PRIVATE);//设置锁频显示
            manager.createNotificationChannel(channel);
            builder = new android.app.Notification.Builder(this,"default");
        }else {
            builder = new android.app.Notification.Builder(this);
        }

        Intent intent = new Intent(getApplicationContext(),ReportRepairActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentTitle(title)
                .setContentText(text)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher);
        android.app.Notification build = builder.build();
        build.flags = Notification.FLAG_AUTO_CANCEL;  //设置点击消失
        manager.notify(post,build);
    }

}
